package com.songcan.oauth.confinguration;

import com.songcan.common.contans.CacheAuthContans;
import com.songcan.common.vo.UserDetailsNew;
import com.songcan.oauth.client.ClientService;
import com.songcan.oauth.compent.OauthUserDetailsService;
import com.songcan.oauth.handle.YfWebResponseExceptionTranslator;
import com.songcan.oauth.provider.YfTokenService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
@EnableAuthorizationServer
@Order(80)
public class AuthenServiceConfiguration  extends AuthorizationServerConfigurerAdapter {


    private  DataSource dataSource;
    private  OauthUserDetailsService userDetailsService;
    private  AuthenticationManager authenticationManager;
    private RedisTemplate<String,Object> redisTemplate;
    private ClientService clientService;


    @Autowired
    public AuthenServiceConfiguration(DataSource dataSource,ClientService clientService,
                                      OauthUserDetailsService userDetailsService,
                                      RedisTemplate redisTemplate,AuthenticationManager authenticationManager){
        this.dataSource = dataSource;
        this.userDetailsService = userDetailsService;
        this.authenticationManager = authenticationManager;
        this.redisTemplate = redisTemplate;
        this.clientService = clientService;
    }

    @Override
    @SneakyThrows
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientService());
    }


    private ClientService clientService(){
        ClientService clientService = new ClientService(dataSource);
        clientService.setSelectClientDetailsSql(CacheAuthContans.DEFAULT_SELECT_STATEMENT);
        clientService.setFindClientDetailsSql(CacheAuthContans.DEFAULT_FIND_STATEMENT);
        return clientService;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                .allowFormAuthenticationForClients()
                .checkTokenAccess("permitAll()");
    }




    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        endpoints.tokenStore(tokenStore());
        endpoints.authenticationManager(authenticationManager);
        endpoints.setClientDetailsService(clientService);
        endpoints.userDetailsService(userDetailsService);
        endpoints.authenticationManager(authenticationManager);
        endpoints.reuseRefreshTokens(true);
        endpoints.tokenServices(tokenServices());
/*        endpoints.tokenServices(tokenUtil());*/
        endpoints.accessTokenConverter(new DefaultAccessTokenConverter());
        endpoints.pathMapping("/oauth/confirm_access", "/token/confirm_access");
        endpoints.exceptionTranslator(new YfWebResponseExceptionTranslator());
    }




    private TokenStore tokenStore(){
        RedisTokenStore yfRedisTokenStore = new RedisTokenStore(redisTemplate.getConnectionFactory());
        return  yfRedisTokenStore;
    }




    public YfTokenService tokenServices() {
        YfTokenService tokenServices = new YfTokenService();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setReuseRefreshToken(true);
        tokenServices.setTokenEnhancer(tokenEnhancer());
        tokenServices.setClientDetailsService(clientService);
        tokenServices.setAuthenticationManager(authenticationManager);
        return  tokenServices;
    }






    private TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            final Map<String, Object> additionalInfo = new HashMap<>(4);
            UserDetailsNew userDetailsNew = (UserDetailsNew) authentication.getUserAuthentication().getPrincipal();
            additionalInfo.put(CacheAuthContans.DETAILS_LICENSE, CacheAuthContans.PROJECT_LICENSE);
            additionalInfo.put(CacheAuthContans.DETAILS_USER_ID, userDetailsNew.getUserId());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        };

    }
}
